package top.dotgo.service.base;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * @author jornl
 * @date 2019-10-13 20:40:32
 */
@Configuration
public class TransactionConfiguration {
    private static final String PROPAGATION_NAME_CHANGE = "PROPAGATION_REQUIRED,-Exception";
    private static final String PROPAGATION_NAME_SELECT = "PROPAGATION_REQUIRED,-Exception,readOnly";


    @Bean(name = "transactionManagerAdvice")
    public TransactionInterceptor transactionInterceptor(PlatformTransactionManager transactionManager) {
        Properties properties = new Properties();
        properties.setProperty("*", PROPAGATION_NAME_SELECT);

        properties.setProperty("add*", PROPAGATION_NAME_CHANGE);
        properties.setProperty("save*", PROPAGATION_NAME_CHANGE);
        properties.setProperty("insert*", PROPAGATION_NAME_CHANGE);
        properties.setProperty("update*", PROPAGATION_NAME_CHANGE);
        properties.setProperty("delete*", PROPAGATION_NAME_CHANGE);
        properties.setProperty("register*", PROPAGATION_NAME_CHANGE);

        return new TransactionInterceptor(transactionManager, properties);
    }


    @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setInterceptorNames("transactionManagerAdvice");
        beanNameAutoProxyCreator.setBeanNames("*Service", "*ServiceImpl");
        beanNameAutoProxyCreator.setProxyTargetClass(true);
        return beanNameAutoProxyCreator;
    }
}
